//
//  NetWorkRequest.m
//  SFASalesReport
//
//  Created by Jonas on 16/8/23.
//  Copyright © 2016年 Jonas. All rights reserved.
//

#import "NetWorkRequest.h"
#include <sys/types.h>
#include <sys/sysctl.h>
#import "AppSetting.h"


@implementation NetWorkRequest

// MARK: -  只要是工作台都是走的这个调用方法---除了版本号检测---
+ (AFHTTPSessionManager *)requestBaseUrlManager {
    NSString *urlString = [AppSetting shareAppSetting].baseUrlString;
    NSURL *baseUrl = [NSURL URLWithString:urlString];
    // MARK: -  这里需要动态的改变token的值就行了------登录的时候每次每次从三星或者强生出来就动态的改变token的值-------
    //给出一个是否是工作台的标记  进入时候赋值为1---
    //发送请求时候做出判断如果是1就让token为工作台的token
    NSString *accessToken = [AppSetting shareAppSetting].accessToken;
//    if ([AppSetting shareAppSetting].alIsSunsumg == YES) {
//        accessToken = [AppSetting shareAppSetting].accessToken;
//    }
//    else {
//        accessToken = [AppSetting shareAppSetting].alAccessToken;
//    }
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl];
    //获取版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString * app_Version = [infoDic objectForKey:@"CFBundleShortVersionString"];
    UIDevice *device = [[UIDevice alloc] init];
    NSString *systemVersion = device.systemVersion;//获取当前系统的版本
    NSString *model = [self getCurrentDeviceModel];      //获取设备的类别
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                                    (CFStringRef)model,
                                                                                                    NULL,
                                                                                                    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                                    kCFStringEncodingUTF8));
    
    NSString *msg = [NSString stringWithFormat:@"com.tongbright.client/%@(iOS;%@;%@;%f)",app_Version,systemVersion,encodedString,[[UIScreen mainScreen] scale]];
    [manager.requestSerializer setValue:accessToken forHTTPHeaderField:@"AccessToken"];
    [manager.requestSerializer setValue:msg forHTTPHeaderField:@"User-Agent"];
    //如果是促销员-------------
//    if ([[AppSetting shareAppSetting].job isEqualToString:@"5000410"] || [[AppSetting shareAppSetting].job isEqualToString:@"5000490"]) {
//        [manager.requestSerializer setValue:[AppSetting shareAppSetting].storeId forHTTPHeaderField:@"StoreId"];
//    }
    return manager;
}


//获取设备型号
+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7Plus";
    if ([platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7Plus";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    
    return platform;
}

//上传的网址
+ (NSString *)netString:(NSString *)net{
    return net;
//    return [NSString stringWithFormat:@"%@%@",Port,net];
}

//get方法
+ (void)getNetRequestData:(NSString *)getNet parmeters:(NSDictionary *)parmeters response:(void(^)(NSDictionary *))response netError:(void(^)(NSError *))netError {
    AFHTTPSessionManager *manager;
    manager = [self requestBaseUrlManager];
    __weak __typeof(self) weakSelf = self;
    [manager GET:[self netString:getNet] parameters:parmeters progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (STATUS == 200) {
            response(responseObject);
        } else if (STATUS == 403) {
//            UIStoryboard *board = [UIStoryboard storyboardWithName:@"YX" bundle:nil];
//            LoginViewController *lVc = [board instantiateViewControllerWithIdentifier:@"LoginViewController"];
//            if (DEVELOPMENT == 2 || DEVELOPMENT == 3) {
//                [UIApplication sharedApplication].keyWindow.rootViewController = alLoginVc;
//
//            }
            
            // MARK: - 退出到登录界面---保存是否登录为否------
//            [UIApplication sharedApplication].keyWindow.rootViewController = lVc;
            [self lableAction:@"请重新登录"];
        } else {
            [strongSelf lableAction:MSG];
            response(nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        netError(error);
        [strongSelf afnetWorkingErrorMessge:error];
    }];
}

//post方法
+ (void)postNetRequestData:(NSString *)getNet parmeters:(NSDictionary *)parmeters response:(void(^)(NSDictionary *))response netError:(void(^)(NSError *))netError {
    AFHTTPSessionManager *manager;
    manager = [self requestBaseUrlManager];
    __weak __typeof(self) weakSelf = self;
    [manager POST:[self netString:getNet] parameters:parmeters progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (STATUS == 200) {
            response(responseObject);
        } else if (STATUS == 403) {
//            UIStoryboard *board = [UIStoryboard storyboardWithName:@"YX" bundle:nil];
//            LoginViewController *lVc = [board instantiateViewControllerWithIdentifier:@"LoginViewController"];
//            ALLogininController *alLoginVc = [board instantiateViewControllerWithIdentifier:@"ALLoginController"];
//            if (DEVELOPMENT == 2 || DEVELOPMENT == 3) {
//                [UIApplication sharedApplication].keyWindow.rootViewController = alLoginVc;
//
//            }
//            else {
//                [UIApplication sharedApplication].keyWindow.rootViewController = lVc;
//            }
            
            // MARK: - 保存是否登录状态并且把一些信息置空--------------
            [self lableAction:@"请重新登录"];
        } else {
            [strongSelf lableAction:MSG];
            response(nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        netError(error);
        [strongSelf afnetWorkingErrorMessge:error];
    }];
}


//单写登录方法
+ (void)logInResponseParmeters:(NSDictionary *)parmeters response:(void(^)(NSDictionary *response))response netError:(void(^)(NSError *error))netError {
    AFHTTPSessionManager *manager;
    NSString *urlString = [AppSetting shareAppSetting].baseUrlString;
    NSURL *baseUrl = [NSURL URLWithString:urlString];
    manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl];
    manager.requestSerializer.timeoutInterval = 60;
    __weak __typeof(self) weakSelf = self;
    [manager POST:[self netString:@""] parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (STATUS == 200) {
            response(responseObject);
        } else {
            [strongSelf lableAction:MSG];
            response(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        NSLog(@" ------- %@",error);
        netError(error);
        [strongSelf afnetWorkingErrorMessge:error];
    }];
}

//上传数据 签到有图片
+ (void)uplodaDataNet:(NSString *)uploadNet parmeters:(NSDictionary *)parmeters imageMutableArray:(NSMutableArray *)imageMutableArray response:(void (^)(NSDictionary *))response netError:(void (^)(NSError *))netError {
    AFHTTPSessionManager *manager;
    manager = [self requestBaseUrlManager];
    __weak __typeof(self) weakSelf = self;
    [manager POST:[self netString:uploadNet] parameters:parmeters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < imageMutableArray.count; i++) {
            UIImage *image = imageMutableArray[i];
            image = [self fixOrientation:image];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            [formData appendPartWithFileData:imageData name:@"Photos" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (STATUS == 200) {
            response(responseObject);
        } else {
            [strongSelf lableAction:MSG];
            response(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        netError(error);
        [strongSelf afnetWorkingErrorMessge:error];
    }];
    
}

//上传信息错误的原因有哪些
+ (void)afnetWorkingErrorMessge:(NSError *)errorMessge{
    switch (errorMessge.code) {
        case NSFileReadUnknownError | NSFileWriteUnknownError:
            [self lableAction:@"未知原因"];
            break;
        case NSFileReadNoPermissionError | NSFileWriteNoPermissionError:
            [self lableAction:@"权限问题"];
            break;
        case NSFileReadTooLargeError:
            [self lableAction:@"文件太大"];
            break;
        case NSFileReadInvalidFileNameError:
            [self lableAction:@"无效的文件名"];
            break;
        case NSURLErrorNotConnectedToInternet | NSURLErrorCannotConnectToHost | kCFURLErrorNetworkConnectionLost:
            [self lableAction:@"无法连接到服务器"];
            break;
        case NSURLErrorTimedOut:
            [self lableAction:@"请求超时"];
            break;
        case NSURLErrorBadServerResponse:
            [self lableAction:@"无响应"];
            break;
        default:
            [self lableAction:@"请检查你的网络"];
            break;
    }
    
}
//显示的view上的lable 信息提示
+ (void)lableAction:(NSString *)actionMessge{
    [[HelpObject manager] labelActionChenge:actionMessge myView:[UIApplication sharedApplication].keyWindow];
}




+ (UIImage *)fixOrientation:(UIImage *)aImage {
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;  
    }  
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);  
    UIImage *img = [UIImage imageWithCGImage:cgimg];  
    CGContextRelease(ctx);  
    CGImageRelease(cgimg);  
    return img;  
}


//使用测试地址判断是否联网了------------------
+ (BOOL)networkConnectionIsAvailable
{
    SCNetworkReachabilityFlags flags;
    // Recover reachability flags
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"wap.baidu.com" UTF8String]);
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
    CFRelease(reachability);
    //如果不能获取连接标志，则不能连接网络，直接返回
    if(!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}

@end
